#!/usr/bin/env python
#! coding: utf-8
#! python3
# Kazeged 2022

import argparse
import os.path
import random
import GM


#==============================================================================
# Gather arguments
#==============================================================================
def Args():
	parser = argparse.ArgumentParser()
	parser.add_argument( "-p", "--play", default=None, dest="gameFolder", help="Auto load a game folder" )
	parser.add_argument( "-g", "--games-folder", default=None, dest="gamesFolder", help="Change the games folder" )
	parser.add_argument( "-s", "--skip-intro", default=False, action="store_true", dest="skipIntro", help="Skips intro" )
	return parser.parse_args()


#==============================================================================
# Engine intro
#==============================================================================
def engine_intro() :
	clock = GM.pygame.time.Clock()
	
	GM.draw_set_color( (255,255,255) )
	GM.draw_set_halign( GM.fa_center )
	GM.draw_set_valign( GM.fa_middle )
	
	running = True
	counter = 0
	step = 0
	
	titleFont = GM.font_add( None, 64 )
	titleText = "Kazeged"
	
	subFont = GM.font_add( None, 20 )
	subText = GM.choose( ["Stories to tell", "The mane engine", "Always mare", "Horsing around"] )
	
	
	W,H = GM._draw_surface_currentSurface.get_size()
	
	while running:
		
		# Event handling, gets all event from the event queue
		for event in GM.pygame.event.get():
			if event.type == GM.pygame.QUIT:
				running = False
			
		
		# Step
		counter += 1
		if step == 0 :
			C = 192 * min( 1, (counter/63.0) )
			if counter > 63 :
				counter = 0
				step = 1
				
		elif step == 1:
			C = 192
			if counter > 63 :
				counter = 0
				step = 2
				
		elif step == 2:
			C = 192 * (1-min( 1, (counter/31.0) ))
			if counter > 31 :
				running = False
		else :
			C = 255
		
		# Draw
		GM.draw_clear()
		
		r = random.randrange(-2,2)
		GM.draw_set_font( titleFont )
		GM.draw_text_color( ((W/2)+2+r,(H/2)+2+r), titleText, (C,0,0) )
		GM.draw_text_color( ((W/2)-2+r,(H/2)+2+r), titleText, (0,C,0) )
		GM.draw_text_color( ((W/2)+r,(H/2)-2+r), titleText, (0,0,C) )
		GM.draw_text_color( (W/2, H/2), titleText, (0,0,0) )
		
		GM.draw_set_font( subFont )
		GM.draw_text_color( (W/2,(H/2)+64), subText, (C,C,C) )
		
		# surface.fill( blendColor, None, 0x3 ) #0x3 = BLEND_RGB_MULT
		
		GM.pygame.display.flip()
		clock.tick(60)
		GM.pygame.event.poll()
	


#==============================================================================
# Main program
#==============================================================================

engineFolder = os.path.dirname( os.path.realpath( __file__ ) )
args = Args()

# Initialize
clock = GM.pygame.time.Clock()

# Create a surface on screen
background_color = (0,0,0)
screen = GM._draw_surface_currentSurface
display = GM.pygame.Surface( (256, 200) )


# Check parameters: Skip engine intro?
if args.skipIntro == False : engine_intro()

# Check parameters: Change game lib folder?
gamesFolder = engineFolder + "/Games"
if args.gamesFolder :
	if os.path.exists( args.gamesFolder ) :
		gamesFolder = args.gamesFolder
	

# Check parameters: Auto load a game folder?
gameFolder = None
if args.gameFolder :
	if os.path.exists( args.gameFolder ) :
		gameFolder = args.gameFolder
	

# Small interface to choose the game to load if non given
if gameFolder == None :
	GM.draw_set_color( (255,255,255) )
	GM.draw_set_halign( GM.fa_left )
	GM.draw_set_valign( GM.fa_top )
	GM.draw_set_font( None )
	GM.draw_text( (0,0), "Loading game list..." )
	GM.pygame.display.flip()
	
	_, directories, files = next( os.walk( gamesFolder ) )
	
	gameList = []
	
	# Check wich folder is a game
	for directory in directories :
		configFile = os.path.join(gamesFolder,directory, "Kazeged.game")
		if os.path.exists(configFile) :
			with open(configFile, "r") as f: meta = {k:v for k, v in (l.replace("\n", "").split("=") for l in f)}
			print("Game: " + meta["name"])
			meta["path"] = os.path.join(gamesFolder,directory)
			if "icon" in meta: meta["icon"] = GM.pygame.image.load(os.path.join(meta["path"], meta["icon"]))
			else: meta["icon"] = GM.pygame.image.load(engineFolder + "/404.png")
			gameList.append(meta)
		
	
	if len( gameList ) > 0 :
		y = 40
		GM.draw_set_valign( GM.fa_middle )
		for game in gameList :
			GM.draw_text( (40,y+20), game["name"] )
			GM._draw_surface_currentSurface.blit(game["icon"], (4,y+4) )
			y += 40
	else :
		GM.draw_text( (0,16), "No game found." )
	
	# Really dirty debug
	running = True
	while running:
		
		# Event handling, gets all event from the event queue
		for event in GM.pygame.event.get():
			if event.type == GM.pygame.QUIT:
				running = False
			
		
		GM.pygame.display.flip()
		clock.tick(60)
		GM.pygame.event.poll()
	


GM.game_end()
